<template>
  <el-card style="height: 100%;">
    <div class="card-title">健康规则管理</div>
    <div class="search-control">
      <div class="left">
        <el-button type="primary" icon="Plus" @click="openInsertDialog">新增</el-button>
      </div>
    </div>

    <el-table :data="healthRulesList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="星级" align="center">
        <template #default="scope">
          <span v-for="star in scope.row.stars" :key="star">⭐</span>
        </template>
      </el-table-column>
      <el-table-column prop="minScore" label="最低分" align="center"></el-table-column>
      <el-table-column prop="maxScore" label="最高分" align="center"></el-table-column>

      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button type="primary" icon="Edit" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-popconfirm title="是否删除该条数据?" @confirm="deleteRow(scope.row.id)">
            <template #reference>
              <el-button type="danger" icon="DeleteFilled" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalData">
    </el-pagination>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑健康规则' : '新增健康规则'" width="30%">
      <el-form :model="healthRulesForm" ref="formRef" label-width="80px" style="padding: 0px 20px">
        <el-form-item label="最低分" prop="minScore">
          <el-input v-model="healthRulesForm.minScore" type="number"></el-input>
        </el-form-item>
        <el-form-item label="最高分" prop="maxScore">
          <el-input v-model="healthRulesForm.maxScore" type="number"></el-input>
        </el-form-item>
        <el-form-item label="星级" prop="stars">
          <el-input v-model="healthRulesForm.stars" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHealthRules">{{ isEdit ? '编辑' : '新增' }}</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {IHealthRules} from "@/views/main/health/rule/types";
import {addHealthRules, deleteHealthRules, queryRulesList, updateHealthRules} from "@/service/common/health";

export default defineComponent({
  setup() {
    const healthRulesList = ref<IHealthRules[]>([]);
    const healthRulesForm = ref<IHealthRules>({
      id: 0,
      minScore: 0,
      maxScore: 0,
      healthLevel: '',
      stars: 0
    });
    const searchHealthLevel = ref<string>('');
    const currentPage = ref<number>(1);
    const pageSize = ref<number>(10);
    const totalData = ref<number>(0);
    const dialogVisible = ref<boolean>(false);
    const isEdit = ref<boolean>(false);
    const selectedRows = ref<IHealthRules[]>([]);

    const fetchHealthRules = () => {
      queryRulesList(currentPage.value, pageSize.value)
        .then(response => {
          healthRulesList.value = response.records;
          totalData.value = response.total;
        })
        .catch(error => {
          console.error("Error fetching health rules:", error);
        });
    };

    const searchData = () => {
      currentPage.value = 1;
      fetchHealthRules();
    };

    const handleSizeChange = (size: number) => {
      pageSize.value = size;
      fetchHealthRules();
    };

    const handleCurrentChange = (page: number) => {
      currentPage.value = page;
      fetchHealthRules();
    };

    const handleSelectionChange = (val: IHealthRules[]) => {
      selectedRows.value = val;
    };

    const openInsertDialog = () => {
      isEdit.value = false;
      dialogVisible.value = true;
      healthRulesForm.value = {
        id: 0,
        minScore: 0,
        maxScore: 0,
        healthLevel: '',
        stars: 0
      };
    };

    const openEditDialog = (row: IHealthRules) => {
      isEdit.value = true;
      dialogVisible.value = true;
      healthRulesForm.value = { ...row };
    };

    const validateScores = (): boolean => {
      if (healthRulesForm.value.stars <= 0) {
        ElMessage.error("星级不能为0");
        return false;
      }
      if (healthRulesForm.value.minScore > healthRulesForm.value.maxScore) {
        ElMessage.error("最低分不能高于最高分");
        return false;
      }
      if (healthRulesForm.value.maxScore < healthRulesForm.value.minScore) {
        ElMessage.error("最高分不能低于最低分");
        return false;
      }
      return true;
    };

    const saveHealthRules = () => {
      if (!validateScores()) {
        return;
      }

      if (isEdit.value) {
        updateHealthRules(healthRulesForm.value)
          .then(() => {
            dialogVisible.value = false;
            ElMessage.success("健康规则更新成功");
            fetchHealthRules();
          })
          .catch(error => {
            console.error("Error updating health rules:", error);
          });
      } else {
        addHealthRules(healthRulesForm.value)
          .then(() => {
            dialogVisible.value = false;
            ElMessage.success("健康规则新增成功");
            fetchHealthRules();
          })
          .catch(error => {
            console.error("Error adding health rules:", error);
          });
      }
    };

    const deleteRow = (id: number) => {
      deleteHealthRules(id)
        .then(() => {
          ElMessage.success("健康规则删除成功");
          fetchHealthRules();
        })
        .catch(error => {
          console.error("Error deleting health rules:", error);
        });
    };

    onMounted(() => {
      fetchHealthRules();
    });

    return {
      healthRulesList,
      healthRulesForm,
      searchHealthLevel,
      currentPage,
      pageSize,
      totalData,
      dialogVisible,
      isEdit,
      selectedRows,
      fetchHealthRules,
      searchData,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      openInsertDialog,
      openEditDialog,
      saveHealthRules,
      deleteRow
    };
  }
});
</script>

<style scoped>
.card-title {
  font-size: 20px;
  margin-bottom: 20px;
}
.search-control {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.dialog-footer {
  text-align: right;
  padding: 10px 0;
}
</style>
